package com.hxj.ecokey.controller;
import com.hxj.ecokey.entity.User;
import com.hxj.ecokey.mapper.UserMapper; // 修正导入路径
import com.hxj.ecokey.service.UserService;
import com.hxj.ecokey.utils.JwtUtil;
import com.hxj.ecokey.utils.Result;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin(origins = "*")
@RestController
    @RequestMapping("/api/user")
public class UserController {

    private final UserMapper userMapper;
    private final UserService userService;

    // 统一使用构造函数注入
    @Autowired
    public UserController(UserMapper userMapper, UserService userService) {
        this.userMapper = userMapper;
        this.userService = userService;
    }

    // 注册接口
    @PostMapping("/register")
    public Result register(@RequestBody @Valid User user) {
        try {
            // 调用Service进行认证
            User registeredUser = userService.register(user);
            return Result.success("注册成功", registeredUser);
        } catch (RuntimeException e) {
            return Result.fail(e.getMessage());
        }
    }

    // 登录接口
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        try {
            // 调用Service进行认证
            User loggedInUser = userService.login(user.getUsername(), user.getPassword());

            // 生成token
            String token = JwtUtil.generateToken(loggedInUser.getId().toString());

            // 返回用户信息和token
            loggedInUser.setPassword(null);
            Map<String,Object> data = new HashMap<>();
            data.put("user", loggedInUser);
            data.put("token", token);

            return Result.success("登录成功", data);
        } catch (RuntimeException e) {
            return Result.fail(e.getMessage());
        }
    }
}